package com.panopset.sf;

import java.awt.Dimension;
import java.awt.Window;
import java.io.StringWriter;
import java.util.StringTokenizer;

import com.panopset.compat.Strings;
import com.panopset.io.FileProps;
import com.panopset.sf.env.Screener;

/**
 * Preserve frame location and dimensions.
 *
 * @author Karl Dinwiddie
 *
 */
public final class FrameState {

    /**
     * File based properties.
     */
    private final FileProps fp;

    /**
     * com.panopset.fs
     */
    private static final String FRAME_STATE_KEY = "com.panopset.fs";

    /**
     *
     * @param fileProps
     *            File properties to store location and dimensions.
     */
    public FrameState(final FileProps fileProps) {
        fp = fileProps;
    }

    /**
     * @param w
     *            Window to update to last or default location and dimensions
     *            of.
     */
    public void update(final Window w) {
        if (updateFromFileProps(w)) {
            return;
        }
        reset(w);
    }
    


    /**
     * Reset window to defaults.
     * @param w Window to reset.
     */
    public void reset(final Window w) {
    	new FrameDefaults().reset(w);
    }
    
    /**
     * 
     * @param w Window to update from props.
     * @return true if successful.
     */
    private boolean updateFromFileProps(final Window w) {
        String s = fp.get(FRAME_STATE_KEY);
        if (!Strings.isPopulated(s)) {
            return false;
        }
        StringTokenizer st = new StringTokenizer(s, ",");
        if (st.countTokens() != 4) {
            return false;
        }
        try {
            w.setLocation(Integer.parseInt(st.nextToken()),
                    Integer.parseInt(st.nextToken()));
            w.setSize(Integer.parseInt(st.nextToken()),
                    Integer.parseInt(st.nextToken()));
        } catch (NumberFormatException ex) {
            return false;
        }
        return true;
    }

    /**
     *
     * @param w
     *            Window to save location and dimensions of.
     */
    public void save(final Window w) {
        StringWriter sw = new StringWriter();
        sw.append("" + w.getX());
        sw.append("," + w.getY());
        sw.append("," + w.getWidth());
        sw.append("," + w.getHeight());
        fp.put(FRAME_STATE_KEY, sw.toString());
    }
}
